package com.freejava.testactivemq.configuration;


import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTopic;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.config.DefaultJmsListenerContainerFactory;
import org.springframework.jms.config.JmsListenerContainerFactory;
import org.springframework.jms.config.SimpleJmsListenerContainerFactory;
import org.springframework.jms.core.JmsMessagingTemplate;

import javax.jms.ConnectionFactory;
import javax.jms.Queue;
import javax.jms.Topic;

@Configuration
public class ActiveMQConfig {

    // ActiveMQ代理地址，因为是使用了连接池，所以需要一个代理地址
    @Value("${spring.activemq.broker-url}")
    private String brokerUrl;

    // 点对点模式下的队列名
    @Value("${spring.activemq.queue-name}")
    private String queueName;

    // 发布/订阅模式下的主题名称
    @Value("${spring.activemq.topic-name}")
    private String topicName;

    // 登录ActiveMQ后台的账号名
    @Value("${spring.activemq.user}")
    private String username;

    // 登录ActiveMQ后台的密码
    @Value("${spring.activemq.password}")
    private String password;

    @Bean
    public Topic topic() {
        return new ActiveMQTopic(this.topicName);
    }

    @Bean
    public Queue queue() {
        return new ActiveMQQueue(this.queueName);
    }

    @Bean
    public ConnectionFactory connectionFactory() {
        return new ActiveMQConnectionFactory(this.username, this.password, this.brokerUrl);
    }

    @Bean
    public JmsMessagingTemplate jmsMessagingTemplate() {
        return new JmsMessagingTemplate(this.connectionFactory());
    }

    // 点对点模式的消息监听器
    @Bean("queueListener")
    public JmsListenerContainerFactory<?> queueJmsListenerContainerFactory(ConnectionFactory connectionFactory) {
        SimpleJmsListenerContainerFactory myfactory = new SimpleJmsListenerContainerFactory();
        myfactory.setConnectionFactory(connectionFactory);
        myfactory.setPubSubDomain(false);
        return myfactory;
    }

    // 发布/订阅模式下的消息监听器
    @Bean("topicListener")
    public JmsListenerContainerFactory<?> topicJmsListenerContainerFactory(ConnectionFactory connectionFactory) {
        SimpleJmsListenerContainerFactory myfactory = new SimpleJmsListenerContainerFactory();
        myfactory.setConnectionFactory(connectionFactory);
        myfactory.setPubSubDomain(true);
        // 开启持久化订阅
        myfactory.setSubscriptionDurable(true);
        // 设置一个特别的客户端ID
        myfactory.setClientId("100011");
        return myfactory;
    }


}
